<template>
  <page-layout>
    <a-spin :spinning="isLoading">
      <a-card :title="title">
        <template #extra>
          <a-button
            v-for="(btn, btnIndex) in btnGroups"
            :key="btnIndex"
            type="primary"
            class="ml-5"
            @click="handleBtnClick(btn)"
          >
            {{ btn.title }}
          </a-button>
        </template>

        <a-form>
          <a-row type="flex" justify="space-between">
            <a-col
              :span="7"
              v-for="item in baseFields.fields"
              :key="item.field"
            >
              <a-form-item :label="item.title" class="mb-5">
                {{ handleFormEmptyData(baseFields.data[item.field]) }}
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <a-tabs :active-key(v-model)="activeKey" size="small">
          <a-tab-pane key="detail" tab="详情">
            <DetailBaseForm v-if="state.refresh" :data="baseFields.data" />
          </a-tab-pane>
          <a-tab-pane key="process" tab="跟进情况">
            <DetailCreateBy v-if="state.refresh" :data="baseFields.data" @refresh="refresh('process')"/>
          </a-tab-pane>
          <a-tab-pane key="user" tab="联系人">
            <DetailPelPle v-if="state.refresh" :data="baseFields.data" @refresh="refresh('user')"/>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-spin>
  </page-layout>
</template>

<script>
import { ref, reactive, onMounted, nextTick, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import { handleFormEmptyData } from "@/tools/filters";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { isEmpty } from "@/tools/common";
import { selectById } from "@/api/module/school";
import { message } from "ant-design-vue";
import DetailBaseForm from "./components/detail-base-form";
import DetailCreateBy from "./components/detail-create-by";
import DetailPelPle from "./components/detail-pelple.vue";
import dictEnum from "@/const/dict";
import moment from 'moment'
import { getCountry } from '@/api/module/school'

export default {
  components: {
    DetailBaseForm,
    DetailCreateBy,
    DetailPelPle
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    let activeKey = ref("detail");
    const title = ref("学校详情");
    const isLoading = ref(false);
    const state = reactive({
      refresh: true,
    })
    const btnGroups = reactive([
      {
        title: "修改",
        permissionCode: "university:school:edit",
        atClick: () => {
          router.push({
            path: "/university/college-manage/edit",
            query: route.query
          });
        }
      }
    ]);
    const baseFields = reactive({
      fields: [
        { title: "学校名称", field: "schoolEnName" },
        { title: "编码", field: "code" },
        { title: "负责人", field: "schResponsiblePersonName" },
        { title: "跟进进度", field: "schFollowUpProgress" },
        { title: "大学缩写", field: "schUniversityAbbreviation" },
        { title: "创建人", field: "createBy" },
        { title: "创建时间", field: "createTime" }
      ],
      data: {},
      dict: {},
      countryData: [],
      provinceData: {}
    });

    const handleBtnClick = btn => {
      btn.atClick && btn.atClick(btn);
    };

    const refresh = (value) => {
      getDetailById(value)
    }

    const getDataByDict = (data, dictKey) => {
      if (isEmpty(data)) return "-";
      const item = baseFields.dict[dictKey].find(v => v.value == data);
      if (isEmpty(item)) return "-";
      return item.label;
    };
    const getDataById = (value, data, vkey = 'id', nkey = 'name') => {
      if (isEmpty(value)) return "-";
      if (isNaN(Number(value))) return value
      if (isEmpty(data)) return '-' 
      const item = data.find(v => v[vkey] == value);
      if (isEmpty(item)) return "-";
      return item[nkey];
    };

    const getDetailById = async (value) => {
      let res = await selectById({ id: route.query.id });
      if (res.code === 500) return message.error("获取详情失败");
      res.data.files.map(file => (res.data[file.type] = file.name));
      res.data.schIntendedProject = (typeof res.data.schIntendedProject) == 'string'
                                          ? res.data.schIntendedProject.split(',')
                                          : []
      res.data.schOnlineYesno = (typeof res.data.schOnlineYesno) == 'string'
                                    ? res.data.schOnlineYesno.split(',')
                                    : []
      res.data.qualification = (typeof res.data.qualification) == 'string'
                                    ? res.data.qualification.split(',')
                                    : []
      res.data.schProjectType = (typeof res.data.schProjectType) == 'string'
                                    ? res.data.schProjectType.split(',')
                                    : []
      res.data.schNature = getDataByDict(
        res.data.schNature,
        dictEnum.SCH_NATURE
      );
      res.data.schCategory = getDataByDict(
        res.data.schCategory,
        dictEnum.SCH_TYPE
      );
      res.data.schCompetitorYesno = getDataByDict(
        res.data.schCompetitorYesno,
        dictEnum.YES_OR_NO
      );
      res.data.schSchoolSystem = getDataByDict(
        res.data.schSchoolSystem,
        dictEnum.SCH_SYSTEM
      );
      res.data.schFollowUpProgress = getDataByDict(
        res.data.schFollowUpProgress,
        dictEnum.FOLLOW_PROGRESS
      );
      res.data.isGpa = getDataByDict(
        res.data.isGpa,
        dictEnum.YES_OR_NO
      );
      res.data.schStar = getDataByDict(
        res.data.schStar,
        dictEnum.STAR_XJ
      );
      let schIntendedProject = res.data.schIntendedProject.map(item => {
        return getDataByDict(
          item,
          dictEnum.Intention_PROJECT
        );
      })
      if (schIntendedProject.length) {
        res.data.schIntendedProject = schIntendedProject.join(',')
      } else {
        res.data.schIntendedProject = '-'
      }
      let schOnlineYesno = res.data.schOnlineYesno.map(item => {
        return getDataByDict(
          item,
          dictEnum.WKQK
        );
      })
      if (schOnlineYesno.length) {
        res.data.schOnlineYesno = schOnlineYesno.join(',')
      } else {
        res.data.schOnlineYesno = '-'
      }

      let qualification = res.data.qualification.map(item => {
        return getDataByDict(
          item,
          dictEnum.SHC_QUALIFICATION
        );
      })
      if (qualification.length) {
        res.data.qualification = qualification.join(',')
      } else {
        res.data.qualification = '-'
      }
      let schProjectType = res.data.schProjectType.map(item => {
        return getDataByDict(
          item,
          dictEnum.PRO_TYPE
        );
      })
      if (schProjectType.length) {
        res.data.schProjectType = schProjectType.join(',')
      } else {
        res.data.schProjectType = '-'
      }

      res.data.schCountryName = getDataById(
        res.data.schCountry,
        baseFields.countryData
      );
      res.data.schProvinceName = getDataById(
        res.data.schProvince,
        baseFields.provinceData[res.data.schCountry],
      );
      res.data.schStartCooperationTime = res.data.schStartCooperationTime
                ? moment(res.data.schStartCooperationTime).format('YYYY-MM-DD')
                : '-'
      res.data.schEndCooperationTime = res.data.schEndCooperationTime
                ? moment(res.data.schEndCooperationTime).format('YYYY-MM-DD')
                : '-'
      res.data.schEstablishmentTime = res.data.schEstablishmentTime
                ? moment(res.data.schEstablishmentTime).format('YYYY')
                : '-'
      res.data.electronList = []
      res.data.paperList = []
      res.data.schCalendarYearList && res.data.schCalendarYearList.map(item => {

        item.schCyBegindate = item.schCyBegindate
                  ? moment(item.schCyBegindate).format('YYYY-MM-DD')
                  : '-'
        item.schCyExaminationdate = item.schCyExaminationdate
                  ? moment(item.schCyExaminationdate).format('YYYY-MM-DD')
                  : '-'
        item.schHolidaydate = item.schHolidaydate
                  ? moment(item.schHolidaydate).format('YYYY-MM-DD')
                  : '-'
                  return item
      })       
      res.data.schoolSendList && res.data.schoolSendList.map(item => {
        const obj = baseFields.countryData.find(i => i.id == item.schSendCountry)
        item.schSendAddress = (item.schSendStreet || '')
                                    + ', ' + (item.schSendCity || '')
                                    + ', ' + (item.schSendProvince || '')
                                    + ', ' + (obj ? obj.name : '')

        if (item.type == 1) {
          res.data.electronList.push(item)
        } else {
          res.data.paperList.push(item)
        }
        return item;
      })       
      baseFields.data = res.data;
      isLoading.value = false;
      activeKey = ref(value)
      state.refresh = false
      nextTick(() => {
        state.refresh = true
      })
    }

    onActivated(async () => {
      isLoading.value = true;
      baseFields.dict = await getDictByCodesReturnObj([
        dictEnum.YES_OR_NO,
        dictEnum.SCH_TYPE,
        dictEnum.SCH_SYSTEM,
        dictEnum.SCH_NATURE,
        dictEnum.FOLLOW_PROGRESS,
        dictEnum.Intention_PROJECT,
        dictEnum.TRANSFER_POLICY,
        dictEnum.WKQK,
        dictEnum.SHC_QUALIFICATION,
        dictEnum.PRO_TYPE,
        dictEnum.STAR_XJ,
      ]);
      const res = await getCountry({})
      baseFields.countryData = res.data.filter(item => item.parent == 0)
      baseFields.provinceData = baseFields.countryData.reduce((obj, item) => {
        // eslint-disable-next-line no-prototype-builtins
        obj.hasOwnProperty(item.id)
          ? obj[item.id].push(item.child)
          : obj[item.id] = item.child || []
        return obj
      }, {})
      getDetailById()
    });

    return {
      state,
      isLoading,
      title,
      btnGroups,
      baseFields,
      activeKey,
      handleBtnClick,
      handleFormEmptyData,
      refresh
    };
  }
};
</script>
